package com.ckzp.weixin;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ckzp.core.ConfigUtil;
import com.ckzp.core.Results;
import com.ckzp.core.json.Jmode;
import com.ckzp.core.json.JsonUtil;
import com.ckzp.jfinal.system.util.SysWorkLogUtil;
import com.jfinal.kit.HttpKit;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 51594 on 2022/8/15.
 */
public class WxTool {


    /**
     * @return
     */
    public static String getState() {
        return "9981";
    }

    /**
     * @return
     */
    public static String getAppID() {
        return ConfigUtil.getProperty("WX_APPID");
    }


    /**
     * @return
     */
    public static String getAppToken() {
        return ConfigUtil.getProperty("WX_TOKEN");
    }

    /**
     * @return
     */
    public static String getAppAeskey() {
        return ConfigUtil.getProperty("WX_AESKEY");
    }

    /**
     * @return
     */
    public static String getAppAppID() {
        return ConfigUtil.getProperty("APP_APPID");
    }

    /**
     * @return
     */
    public static String getAppAppID2() {
        return ConfigUtil.getProperty("APP_APPID2");
    }

    /**
     * @return
     */
    public static String getAppID2() {
        return ConfigUtil.getProperty("WX_APPID2");
    }


    /**
     * @return
     */
    public static String getAppSecret() {
        return ConfigUtil.getProperty("WX_APPSECRET");
    }


    /**
     * @return
     */
    public static String getAppAppSecret() {
        return ConfigUtil.getProperty("APP_SECRET");
    }



    /**
     * @return
     */
    public static String getAppAppSecret2() {
        return ConfigUtil.getProperty("APP_SECRET2");
    }
    /**
     * @return
     */
    public static String getAppSecret2() {
        return ConfigUtil.getProperty("WX_APPSECRET2");
    }

    /**
     * ]
     *
     * @param return_url
     * @return
     */
    public static String EncodeUrl(String return_url) {
        try {
            return java.net.URLEncoder.encode(return_url, "gb2312");
        } catch (Exception e) {
            return return_url;
        }
    }


    /**
     * 报名跳验证地址
     *
     * @param return_url
     * @return
     */
    public static String getUserAuthUrl(String return_url) {
        return_url = WxTool.EncodeUrl(return_url);
        String appid = getAppID();
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
                + "&redirect_uri=" + return_url + "&response_type=code&scope=snsapi_base&state=" + getState() + "#wechat_redirect";
        return url;
    }

    /**
     * @param return_url
     * @return
     */
    public static String getUserInfoAuthUrl(String return_url) {
        return_url = WxTool.EncodeUrl(return_url);
        String appid = WxTool.getAppID();
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
                + "&redirect_uri=" + return_url + "&response_type=code&scope=snsapi_userinfo&state=" + getState() + "#wechat_redirect";
        return url;
    }

    /**
     * @param return_url
     * @return
     */
    public static String getUserInfoAuthUrl2(String return_url) {
        return_url = WxTool.EncodeUrl(return_url);
        String appid = WxTool.getAppID2();
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
                + "&redirect_uri=" + return_url + "&response_type=code&scope=snsapi_userinfo&state=" + getState() + "#wechat_redirect";
        return url;
    }

    /**
     * 报名跳验证地址
     *
     * @param return_url
     * @return
     */
    public static String getUserAuthUrl2(String return_url) {
        return_url = WxTool.EncodeUrl(return_url);
        String appid = getAppID2();
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
                + "&redirect_uri=" + return_url + "&response_type=code&scope=snsapi_base&state=" + getState() + "#wechat_redirect";
        return url;
    }


    /**
     * 判断是否微信环境
     *
     * @param request
     * @return
     */
    public static boolean isWx(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) userAgent = "";
        userAgent = userAgent.toLowerCase();
        if (userAgent.indexOf("micromessenger") > -1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 取得用户的头像尼称等信息
     *
     * @param openid
     * @return
     */
    public static Map getUserInfo(String openid) {
        String ACCESS_TOKEN = AccessTokenTool.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + ACCESS_TOKEN + "&openid=" + openid + "&lang=zh_CN";
        String htmls = HttpKit.get(url).toString();
        return JSON.parseObject(htmls, Map.class);
    }

    /**
     * 取得用户的头像尼称等信息
     *
     * @param openid
     * @return
     */
    public static Map getSnsUserInfo(String openid, String accesstoken) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accesstoken + "&openid=" + openid + "&lang=zh_CN";
        String htmls = HttpKit.get(url).toString();
        return JSON.parseObject(htmls, Map.class);
    }

    /**
     * 发送业务提醒模板消息
     *
     * @param openid
     * @return
     */
    public static Map sendWeixinMessage(String template_id, String openid, Map datas) {
        return sendWeixinMessage(template_id, openid, datas, "");
    }

    /**
     * 发送业务提醒模板消息
     *
     * @param openid
     * @return
     */
    public static Map sendWeixinMessage(String template_id, String openid, Map datas, String urls) {
        try {
            String ACCESS_TOKEN = AccessTokenTool.getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + ACCESS_TOKEN;
            Map parmas = new HashMap();
            parmas.put("touser", openid);
            parmas.put("template_id", template_id);
            parmas.put("url", urls);
            parmas.put("data", datas);
            String htmls = HttpKit.post(url, JSON.toJSONString(parmas));
            return JSON.parseObject(htmls, Map.class);
        } catch (Exception e) {
            Map ms = new HashMap();
            ms.put("errcode", 9);
            ms.put("errmsg", e.getMessage());
            return ms;
        }
    }

    /**
     * 发送业务提醒模板消息
     *
     * @param openid
     * @return
     */
    public static Map sendWeixinMessage2(String template_id, String openid, Map datas, String urls) {
        try {
            String ACCESS_TOKEN = AccessTokenTool.getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + ACCESS_TOKEN;
            Map parmas = new HashMap();
            parmas.put("touser", openid);
            parmas.put("template_id", template_id);
            parmas.put("url", urls);
            parmas.put("data", datas);
            String htmls = HttpKit.post(url, JSON.toJSONString(parmas));
            return JSON.parseObject(htmls, Map.class);
        } catch (Exception e) {
            Map ms = new HashMap();
            ms.put("errcode", 9);
            ms.put("errmsg", e.getMessage());
            return ms;
        }
    }

    /**
     * 更新微信备注名
     *
     * @param openid
     * @param mark_name
     * @return
     */
    public static Map updateUserRemark(String openid, String mark_name) {
        String ACCESS_TOKEN = AccessTokenTool.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=" + ACCESS_TOKEN;
        Map parmas = new HashMap();
        parmas.put("openid", openid);
        parmas.put("remark", mark_name);
        String htmls = HttpKit.post(url, JSON.toJSONString(parmas));
        return JSON.parseObject(htmls, Map.class);
    }

    /**
     * 更新微信公众号菜单
     *
     * @param menu
     * @return
     */
    public static String updateWxMenu(String menu) {
        String ACCESS_TOKEN = AccessTokenTool.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + ACCESS_TOKEN;
        System.out.println(url);
        return HttpKit.post(url, menu);
    }

    /**
     * 更新微信公众号菜单
     *
     * @return
     */
    public static String getWxMenu() {
        String ACCESS_TOKEN = AccessTokenTool.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + ACCESS_TOKEN;
        System.out.println(url);
        Map parmas = new HashMap();
        return HttpKit.post(url, JSON.toJSONString(parmas));
    }

    public static Map getDataMap(String values, String colors) {
        Map<String, String> m = new HashMap<String, String>();
        m.put("value", values);
        m.put("color", colors);
        return m;
    }

    public static String getUpUrl() {
        String ACCESS_TOKEN = AccessTokenTool.getAccessToken();
        String urls = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + ACCESS_TOKEN + "&media_id=";
        return urls;
    }


    public static String getUpUrl2() {
        String ACCESS_TOKEN = AccessTokenTool.getAccessToken2();
        String urls = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + ACCESS_TOKEN + "&media_id=";
        return urls;
    }

    /**
     * 取得关注公众号的二维码
     * 可以传参数
     *
     * @param qrKey 参数，用户关注后会把该参数推送给后台
     * @return
     */
    public static Results getWxQrCodeUrl(String qrKey) {
        Jmode data = Jmode.n().set("expire_seconds", 2592000).set("action_name", "QR_LIMIT_STR_SCENE").set("action_info", Jmode.n().set("scene", Jmode.n().set("scene_str", qrKey)));
        String URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + AccessTokenTool.getAccessToken();
        Map<String, String> headers = new HashMap<String, String>(16);
        headers.put("Content-Type", "application/json");
        String result = HttpKit.post(URL, null, data.toJson(), headers);
        Map m = JsonUtil.toObject(result, Map.class);
        if (m != null) {
            return Results.n().setMsg("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + m.get("ticket"));
        }
        return Results.n().setCode(9).setMsg("取得二维码失败");
    }

    /**
     * 取得拉起小程序的链接信息
     * <p/>
     * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-scheme/generateScheme.html
     *
     * @param path
     * @param query
     * @return
     */
    public static Results getWxAppScheme(String path, String query) {
        Jmode data = Jmode.n().set("jump_wxa", Jmode.n().set("path", path).set("query", query));
        String URL = "https://api.weixin.qq.com/wxa/generatescheme?access_token=" + AccessTokenTool.getAppAccessToken();
        String json_result = HttpRequest.post(URL).execute().body();
        Jmode result = JSONUtil.toBean(json_result, Jmode.class);
        if (result.getInt("errcode") == 0) {
            return Results.n().setMsg("成功").setKeystring(result.getStr("openlink"));
        }
        return Results.n(9).setMsg("取链接失败");
    }


    public static void main(String[] arg) {
        System.out.println(getWxAppScheme("","").toJson());
    }
}
